import React, { useEffect, useState } from "react";
import NavBarBox from "../../components/NavBar";
import "./index.scss";
import { useNavigate } from "react-router-dom";
const user_id = 1;
const server_id = 110;
const socket = new WebSocket(
  `ws://124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
);
const Server = () => {
  const [chatList, setChatList] = useState([]);
  const [message, setMessage] = useState('');
  const listBox=React.useRef(null);
  const navigate=useNavigate()

  const handleToken=()=>{
    const token=localStorage.getItem('token');
    if(!token){
        navigate('/denglu?from=/server')
    }
  }
  useEffect(() => {
    handleToken();
    socket.addEventListener("open", function () {
      socket.send(
        JSON.stringify({
          type: "getChatList",
        })
      );
    });

    // Listen for messages
    socket.addEventListener("message", function (event) {
      const data = JSON.parse(event.data);
      if (data.type === "getChatList") {
        setChatList(data.data);
      } else if (data.type == "addMessage") {
        // .点击发送按钮，可以将输入的消息展示在聊天框中
        setChatList((prev) => [...prev, data.data]);
      }
    });
  },[]);

  const sendMessage=()=>{
    // 发送消息后，用websocket接收响应的消息，并渲染在页面中
    socket.send(
        JSON.stringify({
          type: "addMessage",
          data:{
            user_id,
            server_id,
            message
          }
        })
      );
      setMessage('')
  }
//   5.当聊天内容超出聊天框后，实现新消息展示在最底部，
// 且能在聊天框中将当前消息完全展示出来（聊天框盒子滚动到最底部）
  useEffect(()=>{
    listBox.current.scrollTop = listBox.current.scrollHeight;
  },[chatList])
  return (
    <div className="server">
      {/* 顶部使用封装的公共标题栏组件实现，并可以返回上一页 */}
      <NavBarBox title={"在线咨询"} />
      <div className="mian">
      {/* 8-1.使用弹性布局实现客服消息和自己消息的左右布局 */}
        <div className="listBox" ref={listBox}>
          {chatList.map((item, index) => {
            return (
              <div className={item.dir == 1 ? "listItem2": "listItem"} key={index}>
                <img
                  src={item.dir == 1 ? item.user_avatar : item.server_avatar}
                  alt=""
                  className="imgBox"
                />
                <div className="msgbox">
                  <div className="text">{item.message}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
      <div className="footer">
        <input type="text" value={message} onChange={(e) => setMessage(e.target.value)} />
        {/* 8-2.底部输入框内容为空，发送按钮为禁用状态 */}
        <button disabled={!message} onClick={sendMessage} style={{
            backgroundColor: message ? "blue" : "gray",
        }}>发送</button>
      </div>
    </div>
  );
};

export default Server;
